﻿using System.Collections.Generic;
using ZhaJinHua.Data.Entities;

namespace ZhaJinHua.Data
{
    public class GroupService
    {
        private static GroupService _instance;
        private Dictionary<int, GroupInfo> groups = new Dictionary<int, GroupInfo>();

        public static GroupService Instance
        {
            get
            {
                lock (CommonHelper.LockObj)
                {
                    return _instance ?? (_instance = new GroupService());
                }
            }
        }

        public GroupInfo Get(int groupId)
        {
            lock (CommonHelper.LockObj)
            {
                if (groups.ContainsKey(groupId))
                {
                    return groups[groupId];
                }
                var newGroup = new GroupInfo();
                newGroup.Id = groupId;
                groups.Add(groupId, newGroup);
                return newGroup;
            }
        }

        public bool HasUser(int groupId, string realName)
        {
            var group = Get(groupId);
            return group.HasUser(realName);
        }

        public bool JoinGroup(int groupId, UserInfo userInfo)
        {
            lock (CommonHelper.LockObj)
            {
                if (HasUser(groupId, userInfo.RealName))
                {
                    return true;
                }
                //var user = UserService.Instance.Login(userInfo.RealName);
                var group = Get(groupId);
                return group.AddUser(userInfo);
            }
        }
    }
}